﻿using System;
using System.Collections.Generic;

using System.Text;
using Portal.Interface;
using Portal.Environment;
using Portal.Language;
using System.Data;
using System.Data.SqlClient;

namespace Portal.CMS
{
    public class Document : WebPart
    {
        public override string WebPartId
        {
            get
            {
                return "Document";
            }
        }

        public override bool IsMainWebPart
        {
            get
            {
                return true;
            }
        }


        public override string Title
        {
            get
            {
                return ResourceBLL.GetText(WebPartId, "Title", "Tài liệu văn bản");
            }
        }

        public override string Description
        {
            get
            {
                return ResourceBLL.GetText(WebPartId, "Description", "");
            }
        }


        public override WebPartInt[] SubWebParts
        {
            get
            {
                WebPartInt[] SubWebParts = new WebPartInt[]{
                    new AddDocument(),new UpdateDocument(),new UploadDocument(),new DocumentItems(),new ReDocumentUpload()
                };
                return SubWebParts;
            }
        }

        public string GetViewDocument(string belongSite, string Subject, string ShortId)
        {
            Subject = Environments.ConvertSubject(Subject);
            string Url = Environments.HttpRoot + "/" + Environments.AppendAlias + "-" + belongSite + "/" + Subject + "-vsdoc-" + ShortId + "."+Environments.Extension;
            if (Environments.MultiLanguageInSite == 1)
            {
                Url = Url + "?lang=" + Environments.ActiveLanguage;
            }
            return Url;
        }


        [AjaxPro.AjaxMethod]
        public string GetHtml(string belongSite)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                Environments.CheckWebPartAllow(WebPartId, true);

                string SelectSite =
                    "<select id=drpSelectSite onchange=javascript:FilterFunc();>";
                string[] Sites = Environments.GetSites();
                for (int iIndex = 0; iIndex < Sites.Length; iIndex++)
                {
                    if (Sites[iIndex].ToLower().Equals(belongSite))
                    {
                        SelectSite += "<option selected value=\"" + Sites[iIndex] + "\">" + Sites[iIndex] + "</option>";
                    }
                    else
                    {
                        SelectSite += "<option value=\"" + Sites[iIndex] + "\">" + Sites[iIndex] + "</option>";
                    }
                }
                SelectSite += "</select>";
                DataTable dtDocument = new DocumentBLL().Reading(belongSite);
                string RetHtml =
                    "   <div>" + ResourceBLL.GetText(WebPartId, "SelectSite", "Site") + ":" + SelectSite + "&nbsp;<input type=button value=\"" + ResourceBLL.GetText(WebPartId, "Go", "Lọc dữ liệu") + "\" onclick=javascript:FilterFunc();>&nbsp;<input type=button onclick=\"javascript:ClientAddDocument();\" value=\"" + ResourceBLL.GetText(WebPartId, "TH_Add", "Thêm") + "\"></div>" +
                    "   <div id=divProcessing></div>";
                if (dtDocument.Rows.Count == 0)
                {
                    RetHtml += "<div class=\"cssNoData\">" + ResourceBLL.GetText(WebPartId, "NoData", "Chưa có dữ liệu nào trong chuyên mục này!") + "</div>";
                }
                else
                {
                    RetHtml +=
                    "   <table>" +
                    "       <tr>" +
                    "           <th>" + ResourceBLL.GetText(WebPartId, "TH_Subject", "Tiêu đề") + "</th>" +
                    "           <th></th>" +
                    "           <th></th>" +
                    "           <th></th>" +
                    "           <th></th>" +
                    "           <th></th>" +
                    "       </tr>";

                    
                    for (int iIndex = 0; iIndex < dtDocument.Rows.Count; iIndex++)
                    {
                        string DocumentId = (string)dtDocument.Rows[iIndex]["DocumentId"];
                        string Subject = (string)dtDocument.Rows[iIndex]["Subject"];
                        string DeleteUrl = "javascript:ClientDeleteDocument('" + DocumentId + "')";
                        string PermissionUrl = "javascript:ShowPermissionFuncForm('" + DocumentId + "')";
                        string DocumentUrl = "javascript:ShowDocument('" + DocumentId + "')";
                        string SyncUrl = "javascript:ClientSyncDocument('" + DocumentId + "')";
                        string ShortId = (string)dtDocument.Rows[iIndex]["ShortId"];
                        string LinkText = GetViewDocument(belongSite, Subject, ShortId);
                        LinkText = LinkText.Substring(LinkText.LastIndexOf("/") + 1);
                        LinkText = "<a target=\"_blank\" href=\"" + Environments.HttpRoot + "/" + Environments.AppendAlias + "-" + belongSite + "/" + LinkText + "\">" + LinkText + "</a>";

                        RetHtml +=
                        "       <tr onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='normal'\">" +
                        "           <td class=cssTdSubjectDocument>" + Subject + "<br><span class=cssLinkNews>" + LinkText + "</span></td>" +
                        "           <td valign=top ><a href=\"javascript:ShowClientUpdateUrlForm('" + DocumentId + "');\">" + ResourceBLL.GetText(WebPartId, "TH_Update", "Cập nhật") + "</a></td>" +
                        "           <td valign=top ><a href=\"" + DeleteUrl + "\">" + ResourceBLL.GetText(WebPartId, "TH_Delete", "Xóa") + "</a></td>" +
                        "           <td valign=top ><a href=\"" + PermissionUrl + "\">" + ResourceBLL.GetText(WebPartId, "TH_Permission", "Phân quyền") + "</a></td>" +
                        "           <td valign=top ><a href=\"" + DocumentUrl + "\">" + ResourceBLL.GetText(WebPartId, "Items", "(Tài liệu)") + "</a></td>" +
                        "           <td valign=top ><a href=\"" + SyncUrl + "\">" + ResourceBLL.GetText(WebPartId, "SyncItem", "(Sync)") + "</a></td>" +
                        "       </tr>";
                    }
                    RetHtml +=
                        "   </table>";
                }
                return RetHtml;
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }

        public override string RenderWebPart(LoadParamCls loadParamCls)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Document));
            string RetHtml =
                WebPartUtilities.AttachJavascript("Portal.CMS", "Document.js") +
                "<div id=divDocumentMain class=cssDivDocument>" + GetHtml("vie") + "</div>";
            return RetHtml;
        }

        [AjaxPro.AjaxMethod]
        public string GetAddNewUrl(string belongSite)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);
                PermissionTypeCls PermissionTypeCls = FindPermissionType("DocumentWebPart");
                Environment.Permission.CheckPermission(Environment.Environments.CurrentLoginUser.LoginName, PermissionTypeCls.PermissionTypeCode, "AddDocument", WebPartId, null, true);

                return Screen.BuildDialogUrl(new ParamCls[]{
                            new ParamCls("WebPartId",new AddDocument().WebPartId),
                            new ParamCls("belongSite",belongSite)
            });
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string GetConfirmDeleteMsg()
        {
            return ResourceBLL.GetText(WebPartId, "ConfirmDeleteMsg", "Bạn đã chắc chắn xóa chưa?");
        }


        [AjaxPro.AjaxMethod]
        public string ServerSideCheckAllowDelete(string DocumentId)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);
                PermissionTypeCls PermissionTypeCls = FindPermissionType("Document");
                DocumentCls DocumentCls = new DocumentBLL().CreateModel(Environments.ActiveLanguage, DocumentId);
                Environment.Permission.CheckPermission(Environment.Environments.CurrentLoginUser.LoginName, PermissionTypeCls.PermissionTypeCode, "DeleteDocument", DocumentId, DocumentCls.Owner, true);

                return "";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideDeleteDocument(string DocumentId)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);
                ServerSideCheckAllowDelete(DocumentId);
                SqlTransaction sqlTransaction = Environment.Environments.CreateTransaction();
                try
                {
                    new DocumentBLL().DeleteDocument(sqlTransaction, DocumentId);
                    sqlTransaction.Commit();
                }
                catch (Exception ex)
                {
                    sqlTransaction.Rollback();
                    throw (ex);
                }
                return ResourceBLL.GetText(WebPartId, "DeleteOkMessage", "Xóa thành công!");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetShowUpdateForm(string DocumentId)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);

                PermissionTypeCls PermissionTypeCls = FindPermissionType("Document");
                DocumentCls DocumentCls = new DocumentBLL().CreateModel(Environments.ActiveLanguage, DocumentId);
                Environment.Permission.CheckPermission(Environment.Environments.CurrentLoginUser.LoginName, PermissionTypeCls.PermissionTypeCode, "UpdateDocument", DocumentId, DocumentCls.Owner, true);

                string UpdateUrl = Screen.BuildDialogUrl(new ParamCls[]{
                        new ParamCls("WebPartId",new UpdateDocument().WebPartId),
                        new ParamCls("DocumentId",DocumentId)
                    });
                return UpdateUrl;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }




        public override FunctionCls[] FunctionList
        {
            get
            {
                return new FunctionCls[]
                {
                    new FunctionCls("ViewDocument",ResourceBLL.GetText(WebPartId,"ViewDocument","Xem nhóm tài liệu văn bản"),WebPartId),
                    new FunctionCls("AddDocument",ResourceBLL.GetText(WebPartId,"AddDocument","Thêm mới nhóm tài liệu văn bản"),WebPartId),
                    new FunctionCls("UpdateDocument",ResourceBLL.GetText(WebPartId,"UpdateDocument","Cập nhật chi tiết"),WebPartId),
                    new FunctionCls("DeleteDocument",ResourceBLL.GetText(WebPartId,"DeleteDocument","Xóa chi tiết"),WebPartId),
                    new FunctionCls("PermissionDocument",ResourceBLL.GetText(WebPartId,"PermissionDocument","Phân quyền nhóm tài liệu văn bản"),WebPartId),
                    new FunctionCls("ShowDocumentItems",ResourceBLL.GetText(WebPartId,"ShowDocumentItems","Xem danh sách tài liệu văn bản"),WebPartId),
                    
                    
                    new FunctionCls("DownloadDocumentItem",ResourceBLL.GetText(WebPartId,"DownloadDocumentItem","Download tài liệu văn bản"),WebPartId),
                    new FunctionCls("ReUploadDocumentItem",ResourceBLL.GetText(WebPartId,"ReUploadDocumentItem","upload lại tài liệu văn bản"),WebPartId),
                    new FunctionCls("NeedCheckPermissionDownload",ResourceBLL.GetText(WebPartId,"NeedCheckPermissionDownload","Cần kiểm tra quyền download tài liệu"),WebPartId),
                    
                    new FunctionCls("AddDocumentItem",ResourceBLL.GetText(WebPartId,"AddDocumentItem","Thêm chi tiết tài liệu"),WebPartId),
                    new FunctionCls("DeleteDocumentItem",ResourceBLL.GetText(WebPartId,"DeleteDocumentItem","Xoá tài liệu upload"),WebPartId),
                    new FunctionCls("SaveDocumentItem",ResourceBLL.GetText(WebPartId,"SaveDocumentItem","Ghi lại chi tiết tài liệu"),WebPartId),
                    new FunctionCls("PermissionDocumentItem",ResourceBLL.GetText(WebPartId,"PermissionDocumentItem","Phân quyền cho từng tài liệu"),WebPartId),


                    new FunctionCls("SyncWithServer",ResourceBLL.GetText(WebPartId,"SyncWithServer","Cập nhật lại máy chủ web public"),WebPartId),
                    new FunctionCls("Publishing",ResourceBLL.GetText(WebPartId,"Publishing","Phát hành lên máy chủ web public"),WebPartId),
                    new FunctionCls("UnPublishing",ResourceBLL.GetText(WebPartId,"UnPublishing","Ngừng phát hành lên máy chủ web public"),WebPartId),
                };
            }
        }

        public override PermissionTypeCls[] PermissionTypes
        {
            get
            {
                return new PermissionTypeCls[]{
                    new PermissionTypeCls("DocumentItems","Tài liệu văn bản (Items)",new string[]{"DeleteDocumentItem","SaveDocumentItem","Publishing","UnPublishing","ReUploadDocumentItem","DownloadDocumentItem","PermissionDocumentItem","NeedCheckPermissionDownload"}),
                    new PermissionTypeCls("Document","Tài liệu văn bản",new string[]{"SyncWithServer","ViewDocument","PermissionDocument","UpdateDocument","DeleteDocument","AddDocumentItem","ShowDocumentItems"}),
                    new PermissionTypeCls("DocumentWebPart","Tài liệu văn bản (Webpart)",new string[]{"AddDocument","PermissionDocument"})
                };
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetShowFormSetPermission(string DocumentId)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);
                PermissionTypeCls PermissionTypeCls = FindPermissionType("Document");
                DocumentCls DocumentCls = new DocumentBLL().CreateModel(Environments.ActiveLanguage, DocumentId);
                Environment.Permission.CheckPermission(Environment.Environments.CurrentLoginUser.LoginName, PermissionTypeCls.PermissionTypeCode, "PermissionDocument", DocumentId, DocumentCls.Owner, true);
                return Environment.Permission.GetPermissionUrl(WebPartId, DocumentId, "Document");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        public override PermissionTypeCls GetServicePermissionType()
        {
            return PermissionTypes[2];
        }


        [AjaxPro.AjaxMethod]
        public string GetProcessingText()
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                string Url = Environment.Environments.GetActiveThemeUrl() + "/Global/Loading.gif";
                return "<img src=\"" + Url + "\"><a class=cssProcessing>" + ResourceBLL.GetText(WebPartId, "ProcessingText", "Đang đọc dữ liệu...") + "</a>";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }




        [AjaxPro.AjaxMethod]
        public string GetDocumentUrl(string DocumentId)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);

                PermissionTypeCls PermissionTypeCls = FindPermissionType("Document");
                DocumentCls DocumentCls = new DocumentBLL().CreateModel(Environments.ActiveLanguage, DocumentId);
                Environment.Permission.CheckPermission(Environment.Environments.CurrentLoginUser.LoginName, PermissionTypeCls.PermissionTypeCode, "ShowDocumentItems", DocumentId, DocumentCls.Owner, true);

                string UpdateUrl = Screen.BuildUrl(new ParamCls[]{
                        new ParamCls("WebPartId",new DocumentItems().WebPartId),
                        new ParamCls("DocumentId",DocumentId)
                    });
                return UpdateUrl;

                
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string ServerSideSyncDocument(string DocumentId)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                new DocumentBLL().SyncDocument(DocumentId);
                return ResourceBLL.GetText(WebPartId, "SyncOk", "Đồng bộ với máy chủ Web thành công!");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetConfirmSyncAllMsg()
        {
            return ResourceBLL.GetText(WebPartId, "ConfirmSyncAllMsg", "Bạn đã chắc chắn update lại dữ liệu tin tức trên máy chủ từ máy local chưa?");
        }
    }
}
